package monster.com.cvh.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.BaseRequest;
import com.lzy.okgo.request.PostRequest;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.Permission;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.config.ISCameraConfig;
import com.yuyh.library.imgsel.config.ISListConfig;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileBatchCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BaseBottomDialog;
import me.shaohui.bottomdialog.BottomDialog;
import monster.com.cvh.R;
import monster.com.cvh.activity.base.PermissionActivity;
import monster.com.cvh.adapter.FeedBackPicAdapter;
import monster.com.cvh.bean.FeedBackPicBean;
import monster.com.cvh.bean.PostBean;
import monster.com.cvh.manager.DialogManager;
import monster.com.cvh.util.FileUtils;
import monster.com.cvh.util.KeyboardUtils;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.SPUtils;
import monster.com.cvh.util.StatusBarUtil;
import okhttp3.Call;
import okhttp3.Response;

/**
 * @author: pengguanming
 * @data: 2018/10/24
 * @function:意见反馈Activity
 */
public class FeedbackActivity extends PermissionActivity {
    private static final int REQUEST_LIST_CODE = 0x9000;//跳转到图库的结果码
    private static final int REQUEST_CAMERA_CODE = 0x9001;//拍照结果码
    private static final int MAX_PHOTO_COUNT = 3;//最大图片数

    @BindViews({R.id.tv_activity_feedback_desc_exception, R.id.tv_activity_feedback_desc_advice,
            R.id.tv_activity_feedback_desc_ui, R.id.tv_activity_feedback_desc_other})
    public List<TextView> mTvDescList;

    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.edt_activity_feedback_content)
    EditText mEdtContent;
    @BindView(R.id.tv_activity_feedback_count)
    TextView mTvCount;
    @BindView(R.id.recyclerview_activity_feed_back)
    RecyclerView mRecyclerView;
    @BindView(R.id.edt_activity_feedback_contact)
    EditText mEdtContact;

    private View mFooter;
    private BaseBottomDialog mBottomDialog;

    private List<String> mData = new ArrayList<>();
    private FeedBackPicAdapter mAdapter;
    private String mContract = "";//联系方式
    private String mDescContent = "";//描述内容
    private StringBuffer mTypes = new StringBuffer();//问题类型
    private boolean mIsSelect = false;//是否选中问题类型tab
    private String mCacheFilePath;

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_feedback_layout;
    }

    @Override
    protected void initEvent() {
        StatusBarUtil.setStatusBarLightMode(this, Color.WHITE);
        mTvTitle.setText("意见反馈");
        
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        mFooter = LayoutInflater.from(this).inflate(R.layout.item_feedback_footer, null, false);
        //尾部添加图片的布局
        mFooter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomDialog.show(getSupportFragmentManager());
            }
        });
        mAdapter.addFooterView(mFooter, 0, LinearLayout.HORIZONTAL);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(FeedbackActivity.this, PicLookActivity.class);
                Bundle bundle = new Bundle();
                ArrayList<FeedBackPicBean> feedBackPicBeans=new ArrayList<>();
                for (String path : mAdapter.getData()) {
                    feedBackPicBeans.add(new FeedBackPicBean(path));
                }
                bundle.putParcelableArrayList("feedBackPicBeans",feedBackPicBeans);
                bundle.putInt("index",position);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        
        createBottomDialog();
        mEdtContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String rest = String.valueOf(50 - s.length());
                mTvCount.setText(rest);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    

    @Override
    protected void initData() {
        mCacheFilePath = Environment.getExternalStorageDirectory().getPath() + "/Android/data/" + getPackageName() + "/tiny/";
        mAdapter = new FeedBackPicAdapter(mData);
    }

    @OnClick({R.id.iv_news_details_title_back, R.id.tv_activity_feedback_desc_exception, R.id.tv_activity_feedback_desc_advice,
            R.id.tv_activity_feedback_desc_ui, R.id.tv_activity_feedback_desc_other, R.id.tv_activity_feedback_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_news_details_title_back:
                KeyboardUtils.hideSoftInput(this);
                finish();
                break;
            case R.id.tv_activity_feedback_desc_exception:
                toggleSelect(0);
                break;
            case R.id.tv_activity_feedback_desc_advice:
                toggleSelect(1);
                break;
            case R.id.tv_activity_feedback_desc_ui:
                toggleSelect(2);
                break;
            case R.id.tv_activity_feedback_desc_other:
                toggleSelect(3);
                break;
            case R.id.tv_activity_feedback_commit:
                checkFeedback();
                break;
        }
    }

    private void createBottomDialog() {
        mBottomDialog = BottomDialog.create(getSupportFragmentManager())
                .setViewListener(new BottomDialog.ViewListener() {
                    @Override
                    public void bindView(View v) {
                        v.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mBottomDialog.dismiss();
                            }
                        });
                        v.findViewById(R.id.iv_takephoto).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ISCameraConfig config = new ISCameraConfig.Builder()
                                        .needCrop(false)
                                        .build();

                                ISNav.getInstance().toCameraActivity(FeedbackActivity.this, config, REQUEST_CAMERA_CODE);
                                mBottomDialog.dismiss();
                            }
                        });
                        v.findViewById(R.id.iv_selectpic).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                requestPermission(new Action() {
                                    @Override
                                    public void onAction(Object data) {
                                        openGallery();
                                        mBottomDialog.dismiss();
                                    }
                                }, null, Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE);
                            }
                        });
                    }
                })
                .setLayoutRes(R.layout.bottom_layout)
                .setDimAmount(0.5f)
                .setCancelOutside(true)
                .setTag("BottomDialog");
    }

    public void checkFeedback() {
        mDescContent = mEdtContent.getText().toString().trim();
        mContract = mEdtContact.getText().toString().trim();
        ArrayList<String> tempArray = new ArrayList<>();
        //清空内容
        mTypes.setLength(0);
        for (int i = 0; i < mTvDescList.size(); i++) {
            TextView textView = mTvDescList.get(i);
            if (textView.isSelected()) {
                mIsSelect = true;
                tempArray.add(String.valueOf(i));
            }
        }

        for (int i = 0; i < tempArray.size(); i++) {
            mTypes.append(tempArray.get(i));
            if (i!=tempArray.size()-1){
                mTypes.append(",");
            }
        }

        if (!mIsSelect) {
            showToastShort("请必须选中一个问题类型标签");
            return;
        }

        if (TextUtils.isEmpty(mDescContent)) {
            showToastShort("请填写意见和建议");
            return;
        }

        if (mAdapter != null && mAdapter.getData().size() > 0) {
            List<String> data = mAdapter.getData();
            String[] filePath = data.toArray(new String[data.size()]);
            compressFile(filePath);
        } else {
            uploadFeedback(null);
        }
    }

    /**
     * 压缩选项保持原图尺寸
     *
     * @param filePath
     */
    private void compressFile(String[] filePath) {
        DialogManager.getInstance(this).showProgressDialog(this);
        Tiny.BatchFileCompressOptions options = new Tiny.BatchFileCompressOptions();
        //是否保持原图尺寸
        //options.isKeepSampling = true;
        Tiny.getInstance().source(filePath).batchAsFile().withOptions(options).batchCompress(new FileBatchCallback() {
            @Override
            public void callback(boolean isSuccess, String[] outfile, Throwable t) {
                if (isSuccess) {
                    uploadFeedback(outfile);
                }
                DialogManager.getInstance(FeedbackActivity.this).dismissProgressDialog();
            }
        });
    }

    /**
     * 上传意见反馈
     */
    private void uploadFeedback(final String[] filePath) {
        PostRequest request = OkGo.<String>post(MyConstant.FEED_BACK)
                .params("token", SPUtils.getString(this, "token", ""))
                .params("contact", mContract)
                .params("advice_type", mTypes.toString())
                .params("description", mDescContent);
        //添加图片参数
        if (filePath != null && filePath.length > 0) {
            for (int i = 0; i < filePath.length; i++) {
                request.params("file" + (i + 1), new File(filePath[i]));
            }
        }
        request.execute(new StringCallback() {

            @Override
            public void onBefore(BaseRequest request) {
                DialogManager.getInstance(FeedbackActivity.this).showProgressDialog(FeedbackActivity.this);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.e("Jjy", response.toString() + ";s:" + s);
                //删除压缩后的临时图片
                FileUtils.deleteAllInDir(mCacheFilePath);
                PostBean bean = new Gson().fromJson(s, PostBean.class);
                switch (bean.getCode()) {
                    case 1:
                        finish();
                        startActivity(new Intent(FeedbackActivity.this, FeedBackSuccessActivity.class));
                        break;
                    case -1002:
                    case -1003:
                        showToastLong("登录已经过期，请退出重新登录");
                        startActivity(new Intent(FeedbackActivity.this, LoginActivity.class));
                        finish();
                        break;
                    case -154:
                        showToastLong("请将信息填写完整");
                        break;
                }
            }

            @Override
            public void onAfter(String s, Exception e) {
                DialogManager.getInstance(FeedbackActivity.this).dismissProgressDialog();
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                Log.e("Jjy", response.toString());
            }
        });
    }

    /**
     * 设置问题反馈类型的选中状态
     *
     * @param index
     */
    private void toggleSelect(int index) {
        TextView textView = mTvDescList.get(index);
        if (textView != null) {
            textView.setSelected(!textView.isSelected());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //图片选择结果
        if (requestCode == REQUEST_LIST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra("result");
            for (String path : pathList) {
                if (mAdapter != null) {
                    mAdapter.addData(path);
                }
            }
        }

        //拍照的回调
        if (requestCode == REQUEST_CAMERA_CODE && resultCode == RESULT_OK && data != null) {
            String path = data.getStringExtra("result"); // 图片地址
            if (mAdapter != null) {
                mAdapter.addData(path);
            }
        }

        //根据图片挑选数量，控制尾部添加icon的显示还是隐藏
        if (mAdapter != null && mAdapter.getData() != null) {
            int visiable = mAdapter.getData().size() >= MAX_PHOTO_COUNT ? View.GONE : View.VISIBLE;
            mAdapter.getFooterLayout().setVisibility(visiable);
        }
    }

    /**
     * 跳转到图库
     */
    private void openGallery() {
        // 自由配置选项
        ISListConfig config = new ISListConfig.Builder()
                // 是否多选, 默认true
                .multiSelect(true)
                // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                .rememberSelected(false)
                // “确定”按钮背景色
                .btnBgColor(Color.TRANSPARENT)
                // “确定”按钮文字颜色
                .btnTextColor(getResources().getColor(android.R.color.white))
                // 使用沉浸式状态栏
                .statusBarColor(getResources().getColor(R.color.colorPrimary))
                // 返回图标ResId
                .backResId(R.mipmap.general_back)
                // 标题
                .title("请选择图片")
                // 标题文字颜色
                .titleColor(Color.WHITE)
                // TitleBar背景色
                .titleBgColor(getResources().getColor(R.color.colorPrimary))
                // 第一个是否显示相机，默认true
                .needCamera(true)
                .maxNum(MAX_PHOTO_COUNT - mData.size())
                .build();
        // 跳转到图片选择器
        ISNav.getInstance().toListActivity(this, config, REQUEST_LIST_CODE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mTvDescList != null) {
            mTvDescList.clear();
            mTvDescList = null;
        }
        DialogManager.getInstance(this).dismissProgressDialog();
        OkGo.getInstance().cancelTag(this);
    }
}
